from typing import List
from rikapycli.Result import Result
from rikapycli.CommandManager import CommandManager
from rikapycli.Utils import parse


class Commander:

    def __init__(self, base_command_manager: CommandManager) -> None:
        self.cm: CommandManager = base_command_manager
        self.history: List[str] = []
        self.history_index: int = 0
        self.temp_command: str = ''

    def commit(self, command: str) -> Result:
        """ 执行命令并记录命令，返回结果

        Args:
        - comment: 要执行的指令
        """
        command = command.strip()
        if command == 'exit':
            import sys
            sys.exit(0)
        self.history.append(command)
        self.history_index = 0
        self.temp_command = ''
        return self.cm.run(parse(command))

    def switch_previous(self, command: str) -> str:
        """ 切换到先前的一条命令，并返回命令字符串

        Args:
        - comment: 当前指令
        """
        if self.history_index == 0:
            self.temp_command = command

        self.history_index -= 1
        if self.history_index < -len(self.history):
            self.history_index = -len(self.history)
        return self.history[self.history_index]

    def switch_next(self, command: str) -> str:
        """ 切换到下一条命令，并返回字符串

        Args:
        - comment: 当前指令
        """
        self.history_index += 1
        if self.history_index < 0:
            return self.history[self.history_index]
        else:
            self.history_index = 0
            return self.temp_command
